# -*- coding: utf-8 -*-
"""
示例，简单说明怎么使用django ,json等实现简单的api返回json字符串
"""
__author__ = 'shu2015626'

from django.views.generic.base import View
# from django.views.generic import ListView

from goods.models import Goods


class GoodsListView(View):
    def get(self, request):
        """
        通过django的view实现商品的列表页
        :param request:
        :return:
        """
        json_list = []
        goods = Goods.objects.all()[:10]

        # # ====================================================
        # 方法1和2,当遇到datetime时，都会报错。该类型用json不能被序列化

        # # 方法1
        # for good in goods:
        #     json_dict = {}
        #     json_dict["name"] = good.name
        #     json_dict["category"] = good.category.name
        #     json_dict['market_price'] = good.market_price
        #     json_list.append(json_dict)

        # from django.http import HttpResponse
        # import json
        #
        # return HttpResponse(json.dumps(json_list), content_type="application/json")
        # # ====================================================

        # # ====================================================
        # # 方法2，这里ImageFieldFile和datetime都会报错
        # from django.forms.models import model_to_dict
        # for good in goods:
        #     json_dict = model_to_dict(good)
        #     json_list.append(json_dict)

        # from django.http import HttpResponse
        # import json
        #
        # return HttpResponse(json.dumps(json_list), content_type="application/json")
        # # ====================================================

        # ====================================================
        # 方法3.使用django自带的serializers
        from django.core import serializers
        # 已经是一个json字符串了
        json_data = serializers.serialize("json", goods)

        # from django.http import HttpResponse
        # return HttpResponse(json_data, content_type="application/json")

        import json
        json_data = json.loads(json_data)

        from django.http import JsonResponse

        return JsonResponse(json_data, safe=False)
        # ====================================================

